<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>nodejs基础 | 学习笔记</title><meta name="author" content="lzoxun"><meta name="copyright" content="lzoxun"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="概念   终端直接输入 node 进入可以运行 node 代码的换叫 REPL 环境  nodejs javascript 运行时 不是语言、不是框架、是一个平台、一个基于v8引擎的js运行环境(宿主环境) 哪里安装nodejs，JavaScript代码就能在哪里运行,nodejs之前一般是在浏览器中运行的 所以NodeJs跨平台 使js可以做很多浏览器网站之外的事情 如:Node的Electro">
<meta property="og:type" content="article">
<meta property="og:title" content="nodejs基础">
<meta property="og:url" content="http://example.com/2023/07/22/server/node/server-nodejs/index.html">
<meta property="og:site_name" content="学习笔记">
<meta property="og:description" content="概念   终端直接输入 node 进入可以运行 node 代码的换叫 REPL 环境  nodejs javascript 运行时 不是语言、不是框架、是一个平台、一个基于v8引擎的js运行环境(宿主环境) 哪里安装nodejs，JavaScript代码就能在哪里运行,nodejs之前一般是在浏览器中运行的 所以NodeJs跨平台 使js可以做很多浏览器网站之外的事情 如:Node的Electro">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png">
<meta property="article:published_time" content="2023-07-22T07:14:09.688Z">
<meta property="article:modified_time" content="2023-07-22T07:14:09.688Z">
<meta property="article:author" content="lzoxun">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png"><link rel="shortcut icon" href="/img/favicon.png"><link rel="canonical" href="http://example.com/2023/07/22/server/node/server-nodejs/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: {"path":"/search.xml","preload":true,"top_n_per_article":1,"unescape":true,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: {"defaultEncoding":2,"translateDelay":0,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"簡"},
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: true,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'nodejs基础',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2023-07-22 15:14:09'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          const now = new Date()
          const hour = now.getHours()
          const isNight = hour <= 6 || hour >= 18
          if (t === undefined) isNight ? activateDarkMode() : activateLightMode()
          else if (t === 'light') activateLightMode()
          else activateDarkMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><script>(()=>{
  const $loadingBox = document.getElementById('loading-box')
  const $body = document.body
  const preloader = {
    endLoading: () => {
      $body.style.overflow = ''
      $loadingBox.classList.add('loaded')
    },
    initLoading: () => {
      $body.style.overflow = 'hidden'
      $loadingBox.classList.remove('loaded')
    }
  }

  preloader.initLoading()
  window.addEventListener('load',() => { preloader.endLoading() })

  if (false) {
    document.addEventListener('pjax:send', () => { preloader.initLoading() })
    document.addEventListener('pjax:complete', () => { preloader.endLoading() })
  }
})()</script><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a href="/" title="学习笔记"><span class="site-name">学习笔记</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">nodejs基础</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-07-22T07:14:09.688Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-07-22T07:14:09.688Z" title="更新于 2023-07-22 15:14:09">2023-07-22</time></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="nodejs基础"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="概念"><a href="#概念" class="headerlink" title="概念"></a>概念</h2><blockquote>
<p>  终端直接输入 node 进入可以运行 node 代码的换叫 REPL 环境</p>
</blockquote>
<h3 id="nodejs"><a href="#nodejs" class="headerlink" title="nodejs"></a>nodejs</h3><ul>
<li>javascript 运行时</li>
<li>不是语言、不是框架、是一个平台、一个基于v8引擎的js运行环境(宿主环境)<ul>
<li>哪里安装nodejs，JavaScript代码就能在哪里运行,nodejs之前一般是在浏览器中运行的</li>
<li>所以NodeJs跨平台</li>
<li>使js可以做很多浏览器网站之外的事情</li>
<li>如:<code>Node的Electron开发的VsCode</code> 、<code>gulp</code>、<code>webpack</code></li>
</ul>
</li>
<li>除了nodejs外js其他宿主环境:浏览器</li>
<li>nodejs通过<code>V8 js引擎</code>，node API将任务放到libuv中(事件循环、文件系统、网络IO、线程池等)</li>
<li>nodejs架构<ul>
<li>js操作与Node提供的API(js编写)</li>
<li>解析js的V8（大部分C++）</li>
<li>libuv(C语言编写)</li>
</ul>
</li>
<li>应用场景<ul>
<li>electron桌面程序开发</li>
<li>前端开发库（npm、yarn…）</li>
<li>使用nodejs作为web开发服务器</li>
<li>通过nodejs完成前后的渲染同构<ul>
<li>在后端执行js代码，渲染出最终的html代码，让浏览器直接解析，优化项目</li>
</ul>
</li>
<li>通过node编写自动化脚本</li>
</ul>
</li>
<li>终端输入node回车，进入nodejs的REPL(交互式测试编程环境)</li>
</ul>
<h3 id="JS-引擎"><a href="#JS-引擎" class="headerlink" title="JS 引擎"></a>JS 引擎</h3><blockquote>
<p>作用:将js转汇编转二进制最终变为cpu可以认识的数据<br>JS 的解释阶段，预处理阶段，执行阶段生成执行上下文，VO，作用域链、回收机制等等</p>
</blockquote>
<ul>
<li>常见的JS引擎<ul>
<li><code>SpiderMonkey</code>:第一款，也是作者<code>Brendan Eich</code>开发的</li>
<li><code>Chakra</code>:微软开发主要<code>IE</code>浏览器</li>
<li><code>JavaScriptCore</code>:浏览器引擎(WebKit)中的内置JS引擎，Apply公司开发(小程序的JsCore)<ul>
<li>WebKit &#x3D; 渲染工作的(WebCore) 与 JS引擎(JavaScriptCore) 组成</li>
</ul>
</li>
<li><code>V8</code>:Google开发<ul>
<li><code>在Chrome中，只有Html的渲染采用了WebKit的WebCore代码，而在JavaScript上，重新搭建了一个NB哄哄的V8引</code></li>
<li><code>谷歌浏览器体验好的原因之一</code>6</li>
</ul>
</li>
</ul>
</li>
</ul>
<h2 id="基础操作"><a href="#基础操作" class="headerlink" title="基础操作"></a>基础操作</h2><h3 id="主要组成部分"><a href="#主要组成部分" class="headerlink" title="主要组成部分"></a>主要组成部分</h3><p><img src= "" data-lazy-src="/../../../static/img/nodejs-model.png" alt="&quot;node模型&quot;">   </p>
<p>Node.js 被分为了四层，分别是 <code>应用层</code>、<code>V8引擎层</code>、<code>Node API</code>层 和 <code>LIBUV层</code>。</p>
<ul>
<li><p>应用层：即 JavaScript 交互层，常见的就是 Node.js 的模块，比如 http，fs</p>
</li>
<li><p>V8引擎层：  即利用 V8 引擎来解析JavaScript 语法，进而和下层 API 交互，(c++)</p>
</li>
<li><p>NodeAPI层：  为上层模块提供系统调用，一般是由 C 语言来实现，和操作系统进行交互 。</p>
</li>
<li><p>LIBUV层： 是跨平台的底层封装，实现了 事件循环、文件操作等，是 Node.js 实现异步的核心 </p>
</li>
<li><p>Node.js 内部都是通过 线程池 来完成异步 I&#x2F;O 操作</p>
<ul>
<li>Node.js 的单线程仅仅是指 JavaScript 运行在单线程中，而并非 Node.js 是单线程。</li>
</ul>
</li>
</ul>
<h3 id="流程"><a href="#流程" class="headerlink" title="流程"></a>流程</h3><ol>
<li><p>执行步骤:</p>
<ol>
<li>用户编写<code>编写fs.readFile()</code></li>
<li>V8拿到用户代码进行翻译，解析 -&gt; 完成之后就可以执行    </li>
<li>执行时经过<code>NODE.js BINDINGS</code>到<code>libuv</code>与操作系统沟通,读取文件内容    </li>
<li>BINDINGS作用是使v8翻译处理的代码能与libuv（独立的库）的代码进行沟通</li>
</ol>
</li>
<li><p>操作文件细节</p>
<ol>
<li>js不能直接对一个文件进行操作</li>
<li>任何程序的文件操作都时需要<code>系统调用</code>(操作系统的文件系统)    </li>
<li>Node通过libuv库来操作文件进行系统调用</li>
</ol>
</li>
<li><p>操作系统提供两种调用方式<code>阻塞调用</code>和<code>非阻塞调用</code></p>
<ol>
<li>阻塞和非阻塞是针对系统调用，是系统(被调用方)提供给外界用户的调用方式</li>
<li>同步和异步是针对用户端来说的 (如同步执行代码会被阻塞,系统不会分配新线程来处理它) ，</li>
<li>客户端完全可以主线程通过异步陆续执行，当某个地方执行到阻塞调用时，新开一个进程让他等，主线程继续执行</li>
<li><code>阻塞</code>    </li>
<li><code>非阻塞</code><ol>
<li>后续代码得不到结果，需要不断<code>轮训操作</code>，或类似方式处理</li>
<li><code>轮训操作</code>libuv的线程池(Thread Pool) 进行处理</li>
<li>当得到结果时就可以将对应的回调放到事件循环(某一个队中)</li>
</ol>
</li>
</ol>
</li>
<li><p>node的事件循环</p>
<ul>
<li>比浏览器多:文件IO操作、数据库、子进程、网络IO、定时器、完成对应操作都回家返回结果和回调放到任务队列中<ul>
<li>事件循环会不断的从任务队列取出对应的事件（回调函数）来执行</li>
<li>事件循环具体来说，是主线程过了一遍，异步操作添加到自己的队列位置后，开始执行各个队列的过程</li>
</ul>
</li>
<li>node每一次事件循环(Tick)都有很多阶段<ul>
<li>定时器（timers）</li>
<li>待定回调(Pending Callback)</li>
<li>idle,prepare:仅系统内部使用</li>
<li>轮询(Poll):检索新的I&#x2F;O事件，执行I&#x2F;O事件的回调<ul>
<li>每次Tick中这个阶段世间会比较长，系统希望io回调尽可能早相应，用户尽早拿到数据来用</li>
<li>甚至会阻塞</li>
</ul>
</li>
<li>检测：setImmediate()回调在这里执行<ul>
<li>立即执行，是说不会保存到其他地方，直接放到check queue中</li>
</ul>
</li>
<li>关闭的回调函数：如 socket.on(“close”,()&#x3D;&gt;{})</li>
<li>node事件循环的队列<ul>
<li>微任务队列<ul>
<li><strong>next tick queue ：</strong>process.nextTick  </li>
<li><strong>other queue ：</strong>Promise.then回调、queueMicrotask</li>
</ul>
</li>
<li>宏任务队列<ul>
<li><strong>timer queue ：</strong>setTimeout、setInterval<ul>
<li>如果时间不是0，只会被系统保存，不会直接放到队列中，要等时间到了，才会加入队列，等待下一次循环才开始执行</li>
<li>如果时间是0，正常情况会在本次循环宏任务最先执行，有时特殊情况不会<ul>
<li>出现这种情况的原因主要和setTimeout的实现代码有关，当我们不传时间参数或者设置为0的时候，nodejs会取值为1，即1ms（在浏览器端可能取值会更大一下，不同浏览器也各不相同），所以在电脑cpu性能够强，能够在1ms内执行到timers phase的情况下，由于时间延迟不满足回调不会被执行，于是只能等到第二轮再执行，这样setInterval就会先执行。</li>
</ul>
</li>
</ul>
</li>
<li><strong>poll quere ：</strong>IO事件</li>
<li><strong>check quere ：</strong>setImmediate<ul>
<li>setImmediate只有IE10+和Node上兼容比较好</li>
</ul>
</li>
<li><strong>close queue ：</strong>close 事件</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
</ol>
<h3 id="特性能"><a href="#特性能" class="headerlink" title="特性能"></a>特性能</h3><blockquote>
<p>Nodejs可以解析js代码，没有浏览器安全级别限制（安全沙箱、同源策略），并提供了很多系统级别API</p>
</blockquote>
<ul>
<li>文件读写（File System）</li>
<li>进程管理（Process）</li>
<li>网路通讯等</li>
</ul>
<h3 id="三大特点"><a href="#三大特点" class="headerlink" title="三大特点:"></a>三大特点:</h3><ul>
<li>事件驱动</li>
<li>非阻塞 I(input)&#x2F;O(output) 输入输出流</li>
<li>基于 chrome V8 runtime 轻量高效</li>
</ul>
<h3 id="运行环境"><a href="#运行环境" class="headerlink" title="运行环境"></a>运行环境</h3><ul>
<li>浏览器<ul>
<li>基本语法 </li>
<li>DOM</li>
<li>BOM</li>
<li>Ajax</li>
<li>系统文件数据库(处于安全性考虑 不能实现)</li>
</ul>
</li>
<li>服务器<ul>
<li>基本语法</li>
<li>操作数据库</li>
<li>操作本地文件</li>
<li>进程管理</li>
<li>网络通讯</li>
</ul>
</li>
</ul>
<h3 id="模块化"><a href="#模块化" class="headerlink" title="模块化"></a>模块化</h3><ul>
<li><p>核心模块(node 软件提供的)</p>
</li>
<li><p>第三方模块(用npm安装)</p>
<ul>
<li>nodemailer</li>
</ul>
</li>
<li><p>自定义模块(一个js文件就是一个模块)</p>
</li>
</ul>
<h4 id="模块操作"><a href="#模块操作" class="headerlink" title="模块操作"></a>模块操作</h4><blockquote>
<p>node使用 CommonJS 规范，浏览器是不支持的</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//由于模块作用域,导入后模块间不会互相污染,必须通过导出才可以在外部调用</span></span><br><span class="line"><span class="keyword">const</span> os = <span class="built_in">require</span>(<span class="string">&quot;os&quot;</span>); <span class="comment">//导入模块</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 默认导出</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(os.<span class="title function_">freemem</span>());</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//导入</span></span><br><span class="line"><span class="keyword">const</span> req = <span class="built_in">require</span>(<span class="string">&quot;./node&quot;</span>);</span><br><span class="line"><span class="title function_">req</span>();</span><br><span class="line">-----------------------------------------------</span><br><span class="line"><span class="comment">// 多个导出1</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span>.<span class="property">export1</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;export1&quot;</span>);</span><br><span class="line">&#125;;</span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span>.<span class="property">export2</span> = <span class="keyword">function</span> (<span class="params"></span>) &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;export2&quot;</span>);</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//多个导出2</span></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = &#123;</span><br><span class="line">    export1,</span><br><span class="line">    export2</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//导入</span></span><br><span class="line"><span class="keyword">const</span> &#123; export1, export2 &#125; = <span class="built_in">require</span>(<span class="string">&quot;./node&quot;</span>);</span><br><span class="line"><span class="title function_">export1</span>();</span><br><span class="line"></span><br><span class="line">--------------------------------------------------</span><br><span class="line"><span class="comment">//exports 是 module.exports 的引用</span></span><br><span class="line"><span class="built_in">exports</span>.<span class="property">export1</span> = export1</span><br><span class="line"><span class="built_in">exports</span>.<span class="property">export2</span> = export2</span><br><span class="line"></span><br><span class="line"><span class="built_in">exports</span> = &#123;xxx,xxx&#125; <span class="comment">//错误引用改变了</span></span><br><span class="line"></span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h3 id="爬虫"><a href="#爬虫" class="headerlink" title="爬虫"></a>爬虫</h3><ol>
<li>获取目标网站 (http.get)</li>
<li>分析网站内容 (cheerio 通过jq选择器获取想要的内容 或直接用正则匹配)</li>
<li>获取有效信息 下载或其他操作</li>
</ol>
<h3 id="express"><a href="#express" class="headerlink" title="express"></a>express</h3><p><a target="_blank" rel="noopener" href="https://www.expressjs.com.cn/">官网</a></p>
<h4 id="api"><a href="#api" class="headerlink" title="api"></a>api</h4><ul>
<li>ip</li>
<li>端口号</li>
<li>pathname</li>
<li>method</li>
<li>接收用户的参数</li>
</ul>
<h4 id="template-V层"><a href="#template-V层" class="headerlink" title="template(V层)"></a>template(V层)</h4><ul>
<li>ejs</li>
<li>pug</li>
<li>jade</li>
<li><a target="_blank" rel="noopener" href="http://www.sunxiaoning.com/language/474.html">art-template</a></li>
<li>将vue当做模板放到后端执行就是vue SSR</li>
</ul>
<p>前后端分离:管理代码方便<br>服务端直接渲染返页面:速度效率快，不方便管理</p>
<h4 id="页面渲染-render"><a href="#页面渲染-render" class="headerlink" title="页面渲染 render"></a>页面渲染 render</h4><ul>
<li>SSR (Server Side render 服务端渲染,返回整个页面)</li>
<li>CSR (Client Side render 客户端渲染,返回数据如JSON)</li>
</ul>
<h3 id="什么是服务器"><a href="#什么是服务器" class="headerlink" title="什么是服务器"></a>什么是服务器</h3><ul>
<li>服务器<ul>
<li>服务器的本质就是一台电脑</li>
<li>服务器软件(如:PHP的apach、Java的tomcat、微软的iis、ngnix、node等)</li>
<li>得到服务器IP和端口号</li>
</ul>
</li>
<li>局域网：服务器通过网线或无线相连接,每个电脑都会有一个IP</li>
<li>外网</li>
<li>IP:找到服务器主机的位置</li>
<li>端口号:找到主机中某个程序的位置(0-65535)<ul>
<li>0-1023： BSD保留端口，也叫系统端口(0不使用)</li>
<li>1024-5000： BSD临时端口,留给应用程序使用</li>
<li>5001-65535：BSD服务器(非特权)端口，用来给用户自定义端</li>
<li>http服务 80,用户访问就不要输入端口号了</li>
</ul>
</li>
</ul>
<h3 id="中间件middlewear"><a href="#中间件middlewear" class="headerlink" title="中间件middlewear"></a>中间件middlewear</h3><ul>
<li>内置中间件(静态资源目录 static)</li>
<li>自定义中间件(全局 局部)</li>
<li>第三方中间件 (如 body-parser)</li>
</ul>
<p>注意next()</p>
<h3 id="静态资源目录-static"><a href="#静态资源目录-static" class="headerlink" title="静态资源目录 static"></a>静态资源目录 static</h3><blockquote>
<p>指定一个目录,目录可以被访问 类似Apache 的www</p>
</blockquote>
<h3 id="图片上传"><a href="#图片上传" class="headerlink" title="图片上传"></a>图片上传</h3><blockquote>
<p>原理:将图片、音乐等要上传的东西转换文数据流,通过ajax或form表单传到服务器，服务器接收这些数据后再写入文件系统之中</p>
</blockquote>
<ol>
<li>安装multer模块<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install multer</span><br></pre></td></tr></table></figure></li>
<li>使用<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> multer = <span class="built_in">require</span>(<span class="string">&#x27;multer&#x27;</span>);</span><br></pre></td></tr></table></figure></li>
<li>设置路径与文件名<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> storage = multer.<span class="title function_">diskStorage</span>(&#123;</span><br><span class="line"></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure></li>
</ol>
<h3 id="api接口"><a href="#api接口" class="headerlink" title="api接口"></a>api接口</h3><ul>
<li>url</li>
<li>方法</li>
<li>参数</li>
<li>结果</li>
</ul>
<h3 id="node-跨域-cors中间件处理"><a href="#node-跨域-cors中间件处理" class="headerlink" title="node 跨域 cors中间件处理"></a>node 跨域 cors中间件处理</h3><h3 id="身份验证"><a href="#身份验证" class="headerlink" title="身份验证"></a>身份验证</h3><p>http请求 无状态 服务器、客户端相互不认识</p>
<ul>
<li>无状态，http的每次请求对服务器来说都是单独的请求，和之前请求没有任何关系</li>
</ul>
<p>基本思路:</p>
<ol>
<li>某个用户登录成功后,将用户相关信息加密,生成一个字符串给前端（通过cookie自动传）</li>
<li>这个用户调用其他接口时，将加密字符串（登录凭证）传给服务器，后端通过这些字符判断用户的身份（通过cookie自动传）</li>
<li>再根据这个用户的权限进行验证，是否可以操作</li>
</ol>
<h4 id="方案一、session-cookie"><a href="#方案一、session-cookie" class="headerlink" title="方案一、session + cookie"></a>方案一、session + cookie</h4><p>相关插件:</p>
<ul>
<li>cookie-parser 解析cookie</li>
<li>express-session<br>或</li>
<li>cookie-session</li>
</ul>
<p>使用步骤:</p>
<ol>
<li>用户输入用户名、密码进行登录</li>
<li>成功后，后端会存一个session，保存用户信息</li>
<li>session值当做cookie内容被种到客户端	</li>
<li>cookie会在请求下一个资源时携带（默认域名为作用域，子域名不会携带）</li>
<li>后端将cookie内容与session值进行对比，相等通过，不相等不通过</li>
<li>缺点:服务器需要存每个用户的session</li>
<li>cookie 不设置过期时间(内存cookie，会话cookie)，浏览器关闭自动删除，设置过期时间（硬盘cookie）浏览器关闭依然存在，过期了才会删除</li>
<li>当访问接口时，发现浏览器cookie存储有，与该接口同域名的cookie，就会自动携带到请求头中</li>
</ol>
<p>缺点<br>    每个http都会携带<br>    大小4kb限制<br>    其他客户端(IOS 安卓) 必须手动设置，与浏览器自动不一致<br>    分布式系统和服务器集群要保证服务器1中的session，要在服务器2、3中正确解析<br>设置cookie</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 客户端设置</span></span><br><span class="line"><span class="variable language_">document</span>.<span class="property">cookie</span>=<span class="string">&#x27;name=lzoxun;max-age=5;&#x27;</span>; <span class="comment">// 5s过期时间</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// koa 后端设置</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// sessin 基于 cookie，只能服务端设置</span></span><br><span class="line"><span class="comment">// npm install koa-session</span></span><br><span class="line"><span class="comment">// 设置 session 到时候 ctx 就会有session这个属性</span></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">Session</span> = <span class="built_in">require</span>(<span class="string">&quot;koa-session&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> session = <span class="title class_">Session</span>(&#123;</span><br><span class="line">    <span class="attr">key</span>: <span class="string">&#x27;sessionid&#x27;</span>,</span><br><span class="line">    <span class="attr">maxAge</span>: <span class="number">5</span> * <span class="number">1000</span>,</span><br><span class="line">    <span class="attr">signed</span>: <span class="literal">true</span>  <span class="comment">//签名</span></span><br><span class="line">&#125;, app)</span><br><span class="line">app.<span class="property">keys</span> = [<span class="string">&#x27;fdsafafsa&#x27;</span>]; <span class="comment">// 签名就要有这个，用户不知道这个就不能正确加解密，session别修改，这边也不会获取</span></span><br><span class="line">app.<span class="title function_">use</span>(session);   </span><br><span class="line"></span><br></pre></td></tr></table></figure>
<h4 id="方案二、jwt-（json-web-token）"><a href="#方案二、jwt-（json-web-token）" class="headerlink" title="方案二、jwt （json web token）"></a>方案二、<a target="_blank" rel="noopener" href="http://jwt.io/">jwt</a> （json web token）</h4><p>使用步骤:</p>
<ul>
<li>用户登录 服务器产生一个token(加密字符串)发送给前端</li>
<li>前端将token进行保存  </li>
<li>前端发起数据请求通过 headers 携带 token</li>
<li>服务器验证token是否合法,如果合法继续操作否则终止操作  </li>
<li>token应用场景:无状态请求、保存用户登录状态、第三方登录…</li>
</ul>
<p>jwt 生成token 的组成部分<br>header<br>    alg : 默认 { algorithm: “HS256”} 对称加密<br>    typ : 固定值<br>payload<br>    用户信息<br>signature<br>    设置 secreKey</p>
<p>生成 header.payload.siggnature 加密后的字符串</p>
<h4 id="密码学"><a href="#密码学" class="headerlink" title="密码学"></a>密码学</h4><p>两种加密方式:<br>非对称加密（又叫公钥加密）:RS256、RSA算法 …<br>    通过私钥产生token、通过公钥解密token<br>    指加密和解密使用不同密钥的加密算法,也称为公私钥加密。<br>    加密过程: 原文 + 公钥 &#x3D; 密文 （项目中好像遇到原文+私钥&#x3D;密文？？）<br>    解密过程: 密文 + 私钥 &#x3D; 原文</p>
<pre><code>相对安全复杂
</code></pre>
<p>对称加密: AES<br>    加密解密预定一个密钥，加密和解密使用相同同密钥的加密算法<br>    加密过程: 原文 + 密钥 &#x3D; 密文<br>    解密过程: 密文 - 密钥 &#x3D; 原文</p>
<pre><code>相对简单快速
</code></pre>
<p>客户端加密的意义<br>    1、如果被抓包，抓走的是明文还是密文，对方都可以拿来登陆，仅有的作用是，如果密码够复杂，对方无法解密，对面就不知道你的真时密码，就不肯拿真实密码去其他平台尝试登陆你的账户</p>
<pre><code>2、类似(姓名、银行卡号、家庭住址。。。) 这种也可以客户端
3、如果可以做到到直接抓包无法登陆,或者不容易登陆 呢
</code></pre>
<p>​    </p>
<p>安全登陆姿势<br>    1、将  密码+时间戳  加密后传输，服务端解密，并按照时间戳3s有效的方式允许登陆.这样也能加强安全性</p>
<p>客户端加服务器解密<br>    客户端通过 <code>crypto-js</code> 将字符串通过指定方式加密，服务器拿到加密串后，可以以同样方式解密，或再次加密。。。</p>
<p>[官网](<a target="_blank" rel="noopener" href="https://www.openssl.org/source/"> https://www.openssl.org/source/</a>)    <a target="_blank" rel="noopener" href="http://slproweb.com/products/Win32OpenSSL.html">下载地址</a></p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">openssl方式</span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">生成私钥</span> </span><br><span class="line">openssl 回车</span><br><span class="line"><span class="meta prompt_">OpenSSL&gt; </span><span class="language-bash">genrsa -out rsa_private_key.pem 2048  <span class="comment">#(-out 文件名 字符数)</span></span> </span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">根据私钥生成公钥</span></span><br><span class="line"><span class="meta prompt_">OpenSSL&gt; </span><span class="language-bash">rsa -<span class="keyword">in</span> rsa_private_key.pem -pubout -out rsa_public_key.pem <span class="comment">#(-in 私钥名 -pubout -out 公钥名)</span></span></span><br></pre></td></tr></table></figure>

<p>对称加密：指加密和解密使用<code>相同密钥</code>的加密算法。对称加密算法用来对敏感数据等信息进行加密,常用的算法包括DES、3DES、AES、DESX、Blowfish、RC4、…</p>
<p>插件  </p>
<ul>
<li><a target="_blank" rel="noopener" href="https://www.npmjs.com/package/jsonwebtoken">jsonwebtoken</a></li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> jwt = <span class="built_in">require</span>(<span class="string">&quot;jsonwebtoken&quot;</span>);</span><br><span class="line"><span class="keyword">const</span> scrict = <span class="string">&quot;jfjdsajfdsajfdsa&quot;</span>; <span class="comment">//私钥 （对称加密解密都是它）</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> playload = &#123;</span><br><span class="line">    <span class="comment">//传递的数据</span></span><br><span class="line">    <span class="attr">us</span>: <span class="number">123</span>,</span><br><span class="line">    <span class="attr">ps</span>: <span class="number">456</span>,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">creatToken</span>(<span class="params">playload</span>) &#123;</span><br><span class="line">    <span class="comment">//产生token</span></span><br><span class="line">    playload.<span class="property">ctime</span> = <span class="title class_">Date</span>.<span class="title function_">now</span>();</span><br><span class="line">    playload.<span class="property">exp</span> = <span class="number">1000</span> * <span class="number">60</span> * <span class="number">30</span>; <span class="comment">//30分钟过期</span></span><br><span class="line">    <span class="comment">// 签名 默认HS256加密方式</span></span><br><span class="line">    <span class="keyword">return</span> jwt.<span class="title function_">sign</span>(playload, scrict);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">checkToken</span>(<span class="params">token</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> <span class="title class_">Promise</span>(<span class="function">(<span class="params">resovle, reject</span>) =&gt;</span> &#123;</span><br><span class="line">        <span class="comment">//验证</span></span><br><span class="line">        jwt.<span class="title function_">verify</span>(token, scrict, <span class="function">(<span class="params">err, data</span>) =&gt;</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (err) &#123;</span><br><span class="line">                <span class="title function_">reject</span>(<span class="string">&quot;token 验证失败&quot;</span>);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//ctime + exp &lt; Data().now 说明超时了 </span></span><br><span class="line">            <span class="title function_">resolve</span>(data);</span><br><span class="line">        &#125;);</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">module</span>.<span class="property">exports</span> = &#123;</span><br><span class="line">    creatToken,</span><br><span class="line">    checkToken,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// token 解码</span></span><br><span class="line"><span class="keyword">var</span> decoded = jwt.<span class="title function_">decode</span>(token, &#123;<span class="attr">complete</span>: <span class="literal">true</span>&#125;);</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<h4 id="密码加密-bcrypt"><a href="#密码加密-bcrypt" class="headerlink" title="密码加密 bcrypt"></a>密码加密 bcrypt</h4><blockquote>
<p>每次加密得到的hash字符串是不一样的,验证时可以通过输入的密码与hash进行匹配</p>
</blockquote>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install bcrypt -S</span><br></pre></td></tr></table></figure>
<h3 id="Express-RMVP-模式"><a href="#Express-RMVP-模式" class="headerlink" title="Express RMVP 模式"></a>Express RMVP 模式</h3><blockquote>
<p>MVC -&gt; MVP|RMVP -&gt; MVVM ,Web 设计模式</p>
</blockquote>
<p><a target="_blank" rel="noopener" href="http://www.ruanyifeng.com/blog/2015/02/mvcmvp_mvvm.html">参考</a></p>
<h4 id="MVC"><a href="#MVC" class="headerlink" title="MVC"></a>MVC</h4><ul>
<li>M:Model,模型层，数据相关的操作</li>
<li>V:View,视图层，用户界面渲染逻辑(html、css…)</li>
<li>C:控制器，js</li>
<li>MVC之间三方都能相互通讯</li>
<li>View层是界面，Controller层是业务逻辑，Model层是数据库访问(WEB接口调用)</li>
</ul>
<h4 id="MVP"><a href="#MVP" class="headerlink" title="MVP"></a>MVP</h4><ul>
<li>M:Model,模型层，数据相关的操作</li>
<li>V:View,视图层，用户界面渲染逻辑(html、css…)</li>
<li>P:Presenter,响应视图指令，同时进行相关业务处理，必要时候获调用 Model 获取底层数据，返回指令结果到视图，驱动视图渲染</li>
<li>MVP中M和V无法通讯<ul>
<li>Model 不再负责业务逻辑和视图变化，只负责底层数据处理</li>
<li>View 层只负责发起指令和根据数据渲染 UI，不再有主动监听数据变化等行为，所以也被称之为被动视图</li>
</ul>
</li>
<li>R:请求,RMVP是通过请求与控制器通讯(如 app.use(“&#x2F;R”,xxx))</li>
</ul>
<h4 id="MVVM"><a href="#MVVM" class="headerlink" title="MVVM"></a>MVVM</h4><ul>
<li>M:Model,模型层，数据相关的操作</li>
<li>V:View,视图层，用户界面渲染逻辑(html、css…)</li>
<li>VM:ViewModel,</li>
<li>与MVP唯一的区别是，它采用双向绑定(data-binding),P虽然能与V相互通信,但是VM与V一端变化另一端直接变化</li>
</ul>
<h3 id="node服务调用谷歌控制台"><a href="#node服务调用谷歌控制台" class="headerlink" title="node服务调用谷歌控制台"></a>node服务调用谷歌控制台</h3><p>node-dev 功能与nodemon类似</p>
<ul>
<li>通过 nodemon –inspect –inspect-brk? server.js 开启服务 </li>
<li>配合debugger使用</li>
<li>谷歌打开地址: chrome:&#x2F;&#x2F;inspect&#x2F;#devices </li>
<li>点击 Open dedicated DevTools for Node -&gt; Connection 添加域名端口号</li>
<li>就能在 Open dedicated DevTools for Node -&gt; console 中天使node项目了</li>
</ul>
<h3 id="开发中常用插件"><a href="#开发中常用插件" class="headerlink" title="开发中常用插件"></a>开发中常用插件</h3><ul>
<li>log4js &#x2F;&#x2F;日志操作</li>
<li>pm2 &#x2F;&#x2F; 自动化部署node项目</li>
</ul>
<p><a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1Ci4y1L7gk?p=7">参考资料</a></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">去年工作总结与2021年工作计划</span><br><span class="line">    在去年一年时间里,逐渐完善了iot管理系统云版本，内网版，三套监控大屏系统，内网版的3D设备系统。移动端微信公众号也逐渐成熟，辉和、通佰、和猎狐三套样式都在维护，企业微信也有一套系统可以查看信息，也能方便维护人员在外面能做一些少量的管理，同时在休息时间学习了uni-app，nodejs，TypeScript，微信小程序以及云开发等新技术</span><br><span class="line">    如果有时间并且公司需要的话在2021年的计划中可以通过uni-app技术为公司开发移动端app、微信小程序、百度小程序、支付宝小程序等各个平台系统，可以通过云服务配合nodejs开发一些简单的服务器功能,不需要额外购买分配服务器，此外新的一年里如果时间计划的话，还会将现有系统进行适当优化，有适合的ui的话也可以计划将界面进行改版</span><br><span class="line"></span><br></pre></td></tr></table></figure>




<p>http-server</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="http://example.com">lzoxun</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://example.com/2023/07/22/server/node/server-nodejs/">http://example.com/2023/07/22/server/node/server-nodejs/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://example.com" target="_blank">学习笔记</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/2023/07/22/tmp/Untitled/" title=""><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info"></div></div></a></div><div class="next-post pull-right"><a href="/2023/07/22/server/node/%E5%88%AB%E4%BA%BA%E7%9A%84%E6%96%87%E6%A1%A3/" title=""><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info"></div></div></a></div></nav></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src= "" data-lazy-src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">lzoxun</div><div class="author-info__description"></div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">108</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">1</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">0</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/liaozhongxun"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/liaozhongxun" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:869664233@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">这是我的文档</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%A6%82%E5%BF%B5"><span class="toc-number">1.</span> <span class="toc-text">概念</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#nodejs"><span class="toc-number">1.1.</span> <span class="toc-text">nodejs</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#JS-%E5%BC%95%E6%93%8E"><span class="toc-number">1.2.</span> <span class="toc-text">JS 引擎</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%9F%BA%E7%A1%80%E6%93%8D%E4%BD%9C"><span class="toc-number">2.</span> <span class="toc-text">基础操作</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%BB%E8%A6%81%E7%BB%84%E6%88%90%E9%83%A8%E5%88%86"><span class="toc-number">2.1.</span> <span class="toc-text">主要组成部分</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B"><span class="toc-number">2.2.</span> <span class="toc-text">流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%89%B9%E6%80%A7%E8%83%BD"><span class="toc-number">2.3.</span> <span class="toc-text">特性能</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%89%E5%A4%A7%E7%89%B9%E7%82%B9"><span class="toc-number">2.4.</span> <span class="toc-text">三大特点:</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%90%E8%A1%8C%E7%8E%AF%E5%A2%83"><span class="toc-number">2.5.</span> <span class="toc-text">运行环境</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E5%8C%96"><span class="toc-number">2.6.</span> <span class="toc-text">模块化</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A8%A1%E5%9D%97%E6%93%8D%E4%BD%9C"><span class="toc-number">2.6.1.</span> <span class="toc-text">模块操作</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%88%AC%E8%99%AB"><span class="toc-number">2.7.</span> <span class="toc-text">爬虫</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#express"><span class="toc-number">2.8.</span> <span class="toc-text">express</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#api"><span class="toc-number">2.8.1.</span> <span class="toc-text">api</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#template-V%E5%B1%82"><span class="toc-number">2.8.2.</span> <span class="toc-text">template(V层)</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E9%A1%B5%E9%9D%A2%E6%B8%B2%E6%9F%93-render"><span class="toc-number">2.8.3.</span> <span class="toc-text">页面渲染 render</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E6%9C%8D%E5%8A%A1%E5%99%A8"><span class="toc-number">2.9.</span> <span class="toc-text">什么是服务器</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E4%B8%AD%E9%97%B4%E4%BB%B6middlewear"><span class="toc-number">2.10.</span> <span class="toc-text">中间件middlewear</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9D%99%E6%80%81%E8%B5%84%E6%BA%90%E7%9B%AE%E5%BD%95-static"><span class="toc-number">2.11.</span> <span class="toc-text">静态资源目录 static</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9B%BE%E7%89%87%E4%B8%8A%E4%BC%A0"><span class="toc-number">2.12.</span> <span class="toc-text">图片上传</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#api%E6%8E%A5%E5%8F%A3"><span class="toc-number">2.13.</span> <span class="toc-text">api接口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#node-%E8%B7%A8%E5%9F%9F-cors%E4%B8%AD%E9%97%B4%E4%BB%B6%E5%A4%84%E7%90%86"><span class="toc-number">2.14.</span> <span class="toc-text">node 跨域 cors中间件处理</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BA%AB%E4%BB%BD%E9%AA%8C%E8%AF%81"><span class="toc-number">2.15.</span> <span class="toc-text">身份验证</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%A1%88%E4%B8%80%E3%80%81session-cookie"><span class="toc-number">2.15.1.</span> <span class="toc-text">方案一、session + cookie</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%96%B9%E6%A1%88%E4%BA%8C%E3%80%81jwt-%EF%BC%88json-web-token%EF%BC%89"><span class="toc-number">2.15.2.</span> <span class="toc-text">方案二、jwt （json web token）</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AF%86%E7%A0%81%E5%AD%A6"><span class="toc-number">2.15.3.</span> <span class="toc-text">密码学</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AF%86%E7%A0%81%E5%8A%A0%E5%AF%86-bcrypt"><span class="toc-number">2.15.4.</span> <span class="toc-text">密码加密 bcrypt</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#Express-RMVP-%E6%A8%A1%E5%BC%8F"><span class="toc-number">2.16.</span> <span class="toc-text">Express RMVP 模式</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#MVC"><span class="toc-number">2.16.1.</span> <span class="toc-text">MVC</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#MVP"><span class="toc-number">2.16.2.</span> <span class="toc-text">MVP</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#MVVM"><span class="toc-number">2.16.3.</span> <span class="toc-text">MVVM</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#node%E6%9C%8D%E5%8A%A1%E8%B0%83%E7%94%A8%E8%B0%B7%E6%AD%8C%E6%8E%A7%E5%88%B6%E5%8F%B0"><span class="toc-number">2.17.</span> <span class="toc-text">node服务调用谷歌控制台</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%BC%80%E5%8F%91%E4%B8%AD%E5%B8%B8%E7%94%A8%E6%8F%92%E4%BB%B6"><span class="toc-number">2.18.</span> <span class="toc-text">开发中常用插件</span></a></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-11/" title="win 11 set">win 11 set</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-gitbash/" title="git bash">git bash</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-wsl/" title="wsl">wsl</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/window/win-main/" title="window">window</a><time datetime="2023-07-22T07:14:09.700Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/2023/07/22/web/%E5%85%BC%E5%AE%B9%E9%97%AE%E9%A2%98/" title="兼容问题">兼容问题</a><time datetime="2023-07-22T07:14:09.699Z" title="发表于 2023-07-22 15:14:09">2023-07-22</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By lzoxun</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="/js/tw_cn.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/instant.page/instantpage.min.js" type="module"></script><script src="https://cdn.jsdelivr.net/npm/vanilla-lazyload/dist/lazyload.iife.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"></div><script id="canvas_nest" defer="defer" color="0,0,255" opacity="0.7" zIndex="-1" count="99" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/canvas-nest.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/js/search/local-search.js"></script></div></div><script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"log":false,"model":{"jsonPath":"/live2dw/assets/haruto.model.json"},"display":{"position":"right","width":100,"height":200,"right":300},"mobile":{"show":true}});</script></body></html>